package com.cy.pj.sys.service.impl;

import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.sys.dao.SysUserDao;
import com.cy.pj.sys.dao.SysUserRoleDao;
import com.cy.pj.sys.pojo.SysUser;
import com.cy.pj.sys.service.SysUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;

    public int updateUser(SysUser entity){
        //开启事务
        //1.参数校验(省略)
        //2.更新用户自身信息
        int rows=sysUserDao.updateUser(entity);
        if(rows==0)
            throw new ServiceException("记录可能已经不存在");
        //3.更新用户和角色关系数据
        sysUserRoleDao.deleteByUserId(entity.getId());
        sysUserRoleDao.insertUserRoles(entity.getId(),
                entity.getRoleIds());
        return rows;
    }
    public SysUser findById(Integer id){
        SysUser user=sysUserDao.selectById(id);
        if(user==null)
            throw new ServiceException("此用户可能已经不存在");
        List<Integer> roleIds=sysUserRoleDao.selectRoleIdsByUserId(id);
        user.setRoleIds(roleIds);
        return user;
    }
//    @Transactional(timeout = 5)
    public int saveUser(SysUser entity){
        //产生一个随机字符串作为加密盐使用
        String salt= UUID.randomUUID().toString();
        //对密码进行 MD5 盐值加密(MD5 特点:不可逆,相同内容加密结果也相同)
        SimpleHash sh=new SimpleHash("MD5",entity.getPassword(),salt,1);
        String hashedPassword=sh.toHex();
        entity.setSalt(salt);
        entity.setPassword(hashedPassword);
        int rows=sysUserDao.insertUser(entity);
        sysUserRoleDao.insertUserRoles(
                entity.getId(),entity.getRoleIds());
        return rows;
    }

    @RequiresPermissions("sys:user:update")
    public int validById(Integer id,Integer valid){
        String modifierUser="admin";
        int rows=sysUserDao.validById(id,valid,modifierUser);
        if(rows==0)throw new ServiceException("记录可能已经不存在");
        return rows;
    }

    public List<SysUser> findUsers(SysUser entity){
        return sysUserDao.selectUsers(entity);
    }


}
